﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XUtility;

namespace XUtility
{
    public class RedisClass
    {
        private static int useDBNum = WebConfig.GetAppSetting("RedisDBNum").ToInt32(4);

        //连接哪个DB
        private static int DBNum = useDBNum;
        private static String SysKey = WebConfig.GetAppSetting("RedisMyKey");

        private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        {
            var config = new ConfigurationOptions();
            config.EndPoints.Add(WebConfig.GetAppSetting("RedisHost") ?? "localhost", 6379);

            config.SyncTimeout = 10000;
            config.AbortOnConnectFail = false;
            config.ResolveDns = false;
            config.Password = WebConfig.GetAppSetting("RedisPwd");

            config.Ssl = false;

            var connectionMultiplexer = ConnectionMultiplexer.Connect(config);
            connectionMultiplexer.PreserveAsyncOrder = false;

            return connectionMultiplexer;
        });

        public static ConnectionMultiplexer Connection
        {
            get
            {
                return lazyConnection.Value;
            }
        }

        private static IDatabase db = Connection.GetDatabase(DBNum);

        /// <summary>
        /// 获取系统的redis key前缀
        /// </summary>
        /// <param name="resourceid">资源Id</param>
        /// <returns></returns>
        public static string GetMyKey(string resourceid = "")
        {
            string Key = "XUtility_" + SysKey + "_";
            if (!string.IsNullOrWhiteSpace(resourceid))
            {
                Key = Key + resourceid;
            }
            return Key;
        }

        #region String 可以设置过期时间

        /// <summary>
        /// 保存单个key value
        /// </summary>
        /// <param name="key">Redis Key</param>
        /// <param name="value">保存的值</param>
        /// <param name="expiry">过期时间</param>
        /// <returns></returns>
        public static bool SetStringKey(string key, string value, TimeSpan? expiry = default(TimeSpan?))
        {
            return db.StringSet(GetMyKey(key), value, expiry);
        }

        /// <summary>
        /// 保存多个key value
        /// </summary>
        /// <param name="arr">key</param>
        /// <returns></returns>
        public static bool SetStringKey(KeyValuePair<RedisKey, RedisValue>[] keyValues)
        {
            List<KeyValuePair<RedisKey, RedisValue>> newkeyValues =
                  keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(GetMyKey(p.Key), p.Value)).ToList();
            return db.StringSet(newkeyValues.ToArray());
        }

        /// <summary>
        /// 保存一个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool SetStringKey<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
        {
            string json = JsonClass.ToJson(obj);
            return db.StringSet(GetMyKey(key), json, expiry);
        }

        /// <summary>
        /// 获取单个key的值
        /// </summary>
        /// <param name="key">Redis Key</param>
        /// <returns></returns>

        public static RedisValue GetStringKey(string key)
        {
            return db.StringGet(GetMyKey(key));
        }


        /// <summary>
        /// 获取多个Key
        /// </summary>
        /// <param name="listKey">Redis Key集合</param>
        /// <returns></returns>
        public static RedisValue[] GetStringKey(List<RedisKey> listKey)
        {
            List<string> newKeys = listKey.Select(q => GetMyKey(q)).ToList();
            return db.StringGet(newKeys.Select(redisKey => (RedisKey)redisKey).ToArray());
        }

        /// <summary>
        /// 获取一个key的对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetStringKey<T>(string key)
        {
            return JsonClass.FromJson<T>(db.StringGet(GetMyKey(key)));
        }


        #endregion

        #region Hash

        /// <summary>
        /// 保存一个集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Redis Key</param>
        /// <param name="list">数据集合</param>
        /// <param name="getModelId"></param>
        public static void HashSet<T>(string key, List<T> list, Func<T, string> getModelId)
        {
            List<HashEntry> listHashEntry = new List<HashEntry>();
            foreach (var item in list)
            {
                string json = JsonClass.ToJson(item);
                listHashEntry.Add(new HashEntry(getModelId(item), json));
            }
            db.HashSet(GetMyKey(key), listHashEntry.ToArray());
        }

        /// <summary>
        /// 获取Hash中的单个key的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Redis Key</param>
        /// <param name="hasFildValue">RedisValue</param>
        /// <returns></returns>
        public static T GetHashKey<T>(string key, string hasFildValue)
        {
            if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(hasFildValue))
            {
                RedisValue value = db.HashGet(GetMyKey(key), hasFildValue);
                if (!value.IsNullOrEmpty)
                {
                    return JsonClass.FromJson<T>(value);
                }
            }
            return default(T);
        }

        /// <summary>
        /// 获取hash中的多个key的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Redis Key</param>
        /// <param name="listhashFields">RedisValue value</param>
        /// <returns></returns>
        public static List<T> GetHashKey<T>(string key, List<RedisValue> listhashFields)
        {
            List<T> result = new List<T>();
            if (!string.IsNullOrWhiteSpace(key) && listhashFields.Count > 0)
            {
                RedisValue[] value = db.HashGet(GetMyKey(key), listhashFields.ToArray());
                foreach (var item in value)
                {
                    if (!item.IsNullOrEmpty)
                    {
                        result.Add(JsonClass.FromJson<T>(item));
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 获取hashkey所有Redis key
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static List<T> GetHashAll<T>(string key)
        {
            List<T> result = new List<T>();
            RedisValue[] arr = db.HashKeys(GetMyKey(key));
            foreach (var item in arr)
            {
                if (!item.IsNullOrEmpty)
                {
                    result.Add(JsonClass.FromJson<T>(item));
                }
            }
            return result;
        }

        /// <summary>
        /// 获取hashkey所有的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static List<T> HashGetAll<T>(string key)
        {
            List<T> result = new List<T>();
            HashEntry[] arr = db.HashGetAll(GetMyKey(key));
            foreach (var item in arr)
            {
                if (!item.Value.IsNullOrEmpty)
                {
                    result.Add(JsonClass.FromJson<T>(item.Value));
                }
            }
            return result;
        }

        /// <summary>
        /// 删除hasekey
        /// </summary>
        /// <param name="key"></param>
        /// <param name="hashField"></param>
        /// <returns></returns>
        public static bool DeleteHase(RedisKey key, RedisValue hashField)
        {
            return db.HashDelete(GetMyKey(key), hashField);
        }

        #endregion

        #region key

        /// <summary>
        /// 删除单个key
        /// </summary>
        /// <param name="key">redis key</param>
        /// <returns>是否删除成功</returns>
        public static bool KeyDelete(string key)
        {
            return db.KeyDelete(GetMyKey(key));
        }

        /// <summary>
        /// 删除多个key
        /// </summary>
        /// <param name="keys">rediskey</param>
        /// <returns>成功删除的个数</returns>
        public static long keyDelete(RedisKey[] keys)
        {
            List<string> newKeys = keys.Select(q => GetMyKey(q)).ToList();
            return db.KeyDelete(newKeys.Select(redisKey => (RedisKey)redisKey).ToArray());
        }

        /// <summary>
        /// 删除指定前缀的key
        /// </summary>
        /// <param name="keyFormatter">指定的前缀</param>
        public static void Clear(String keyFormatter = null)
        {
            db.ScriptEvaluate(LuaScript.Prepare(
                  //Redis的keys模糊查询：
                  " local ks = redis.call('KEYS', @keypattern) " + //local ks为定义一个局部变量，其中用于存储获取到的keys
                  " for i=1,#ks,5000 do " +    //#ks为ks集合的个数, 语句的意思： for(int i = 1; i <= ks.Count; i+=5000)
                  "     redis.call('del', unpack(ks, i, math.min(i+4999, #ks))) " + //Lua集合索引值从1为起始，unpack为解包，获取ks集合中的数据，每次5000，然后执行删除
                  " end " +
                  " return true "),
                 new { keypattern = keyFormatter ?? (GetMyKey() + "*") });

            db.ScriptEvaluate(LuaScript.Prepare(
                 " local ks = redis.call('hkeys', @hashid) " +
                 " local fkeys = {} " +
                 " for i=1,#ks do " +
                 //使用string.find进行匹配操作
                 "   if string.find(ks[i], @keypattern) then " +
                 "      fkeys[#fkeys + 1] = ks[i] " +
                 "   end " +
                 " end " +
                 " for i=1,#fkeys,5000 do " +
                 "   redis.call('hdel', @hashid, unpack(fkeys, i, math.min(i+4999, #fkeys))) " +
                 " end " +
                 " return true "),
                 new { hashid = "hkey", keypattern = keyFormatter ?? (GetMyKey() + "*") });   //keypattern为可使用正则表达式

            db.ScriptEvaluate(LuaScript.Prepare(
                 " local ks = redis.call('smembers', @keyid) " +
                 " local fkeys = {} " +
                 " for i=1,#ks do " +
                 "   if string.find(ks[i], @keypattern) then " +
                 "      fkeys[#fkeys + 1] = ks[i] " +
                 "   end " +
                 " end " +
                 " for i=1,#fkeys,5000 do " +
                 "   redis.call('srem', @keyid, unpack(fkeys, i, math.min(i+4999, #fkeys))) " +
                 " end " +
                 " return true "),
                 new { keyid = "setkey", keypattern = keyFormatter ?? (GetMyKey() + "*") });   //keypattern为可使用正则表达式

        }

        /// <summary>
        /// 判断key是否存储
        /// </summary>
        /// <param name="key">redis key</param>
        /// <returns></returns>
        public static bool KeyExists(string key)
        {
            return db.KeyExists(GetMyKey(key));
        }

        /// <summary>
        /// 重新命名key
        /// </summary>
        /// <param name="key">就的redis key</param>
        /// <param name="newKey">新的redis key</param>
        /// <returns></returns>
        public static bool KeyRename(string key, string newKey)
        {
            return db.KeyRename(GetMyKey(key), newKey);
        }
        #endregion


        /// <summary>
        /// 追加值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void StringAppend(string key, string value)
        {
            ////追加值，返回追加后长度
            long appendlong = db.StringAppend(GetMyKey(key), value);
        }
    }
}
